import {
	post,
	get
} from "@/utils/request.js"

import {
	getTeacherInfo,
	getCurrentBadge,
} from "@/api/user.js"
import {
	login,
} from "@/api/sgw.js"

import config from "@/utils/config.js"

export const toLogin = async (openid, iv, encryptedData, inviter) => {
	// let result = await getcode()
	console.log("toLogin-----", openid, "/------/", iv, "/------/", encryptedData, "/------/", inviter,
		"/------/");
	let params = {
		username: '测试001',
		password: '123456',
	}
	let data = await login(params)
	console.log("获取code", data);
	uni.setStorageSync("token", token)
	let user = await getTeacherInfo()
	console.log(user);
	console.log("获取code");
	// return post('/api/child/list', data)
	return new Promise((resolve, reject) => {
		resolve({
			token: token,
			userInfo: user.data
		});
	});
}

export const getcode = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			success: res => {
				resolve(res.code);
			},
			fail: error => {
				console.log("登录失败:", error);
				reject(error);
			}
		});
	});
}
/**
 * @param {Object} openid 小程序用户openid
 * @param {Object} info 头像相关参数
 * @param {Object} inviter 邀请人ID
 */
function loginSys(openid, iv, encryptedData, inviter) {
	// code是授权码，userinfo是小程序wx.getUserProfile
	// 接口返回的userInfo对象，inviter是邀请人的ID，如果没有就不填，userInfo和code是必填
	var params = {
		openid: openid,
		userInfo: {
			avatarUrl: "",
			city: "",
			country: "",
			gender: "",
			language: "",
			nickName: "",
			province: "",
		},
		inviter: inviter,
		encryptedData: encryptedData,
		iv: iv,
	}
	console.log("params: " + JSON.stringify(params));
	console.log(config.Api + '/api/teacher/auth');
	return new Promise((resolve, reject) => {
		uni.request({
			url: config.Api + '/api/teacher/auth',
			method: 'POST',
			timeout: 12000,
			data: params,
			header: {
				"Content-Type": "application/json",
			},
			success: (res) => {
				if (res.data.code != 200) {
					reject(res.data);
					// uni.showLoading({
					// 	icon: "error",
					// 	title: res.data.message,
					// });
					// setTimeout(() => {
					// 	uni.hideLoading();
					// }, 2000);
				} else {
					resolve(res.data.data);
					// uni.hideLoading()
				}
			},
			fail: (err) => {
				reject(err);
				if (err.errMsg == "request:fail timeout") {
					uni.showLoading({
						icon: "error",
						title: "登录超时"
					});
					setTimeout(() => {
						uni.hideLoading();
					}, 2000);
				}


				console.log("调用接口失败")

			}
		});
	});
}
// 使用示例
// makeRequest('https://api.example.com/data')
//   .then(function(response) {
//     console.log('请求成功:', response);
//   })
//   .catch(function(error) {
//     console.log('请求失败:', error);
//   });

export const toLogout = (data) => {
	return get('/api/teacher/logout', data)
}

export const getOpenid = (data) => {
	return get('/api/teacher/getOpenid/' + data)
}